import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtWidgets import QDialog, QFileDialog, QMessageBox, QDockWidget, QListWidget
from PyQt5.QtGui import *

from Ui_mainwindow import Ui_MainWindow  #导入创建的GUI类

from Ui_textwindow import Ui_textWindow
from Ui_pattern_define import Ui_Dialog_pattern

from Netlist2LOC import *


class outputWindow(QtWidgets.QMainWindow, Ui_textWindow):
    def __init__(self):
        super(outputWindow, self).__init__()
        self.setupUi(self)
class patternDialog(QtWidgets.QDialog, Ui_Dialog_pattern):
    def __init__(self):
        super(patternDialog, self).__init__()
        self.setupUi(self)

#自己建一个mywindows类，mywindow是自己的类名。QtWidgets.QMainWindow：继承该类方法
class mywindow(QtWidgets.QMainWindow, Ui_MainWindow):
    #__init__:析构函数，也就是类被创建后就会预先加载的项目。
    # 马上运行，这个方法可以用来对你的对象做一些你希望的初始化。
    def __init__(self):
        #这里需要重载一下mywindow，同时也包含了QtWidgets.QMainWindow的预加载项。
        super(mywindow, self).__init__()
        self.setupUi(self)
        self.initNetlistDeal()
        self.connSlots()

        self.textWindow = outputWindow()

        self.pattDialog = patternDialog()
        
    


        self.logLines=''
        self.selectedBusDict={}
        self.selectedItemPos=[]
        self.selectedRowNum=[]

        self.menuBar = QtWidgets.QMenuBar(self)
        self.menuBar.setGeometry(QtCore.QRect(0, 0, 606, 26))
        self.menuBar.setObjectName("menuBar")
    def __del__( self):
        if self.textWindow!=None:
            self.textWindow.close()
    def connSlots(self):
        self.pushButton_import.clicked.connect(self.importNetlist)
        self.actionOpen.triggered.connect(self.importNetlist)

        # self.lineEdit.textChanged.connect(self.showSearchResultToList)
        
        self.pushButton_search.clicked.connect(self.showSearchResultToList)

        self.tableView.customContextMenuRequested['QPoint'].connect(self.tableViewMenu)

    def initNetlistDeal(self):
        self.netlistdeal=Netlist2LOC()

    def importNetlist(self):
        self.netlistdeal.clear()
        filename,  _ = QFileDialog.getOpenFileName(self, 'Open file', '', "CSV Files (*.csv)")
        if filename:
            self.netlistdeal.inputFilePath=filename
            self.netlistdeal.genSignalLOCMap()
            self.appendLog(str(len(self.netlistdeal.originNetMap))+' lines of LOC info loaded\n')
            self.setTableViewModel(self.netlistdeal.originNetMap)
           
    def showSearchResultToList(self):
        self.searchType=0
        
        if self.radioButton_searchNet.isChecked():
            self.searchType=0
        elif self.radioButton_searchLOC.isChecked():
            self.searchType=1

        if self.lineEdit_partNameList.text()!='':
            self.netlistdeal.searchPartFilter=self.lineEdit_partNameList.text()
            logLine='Part Filter = '+self.netlistdeal.searchPartFilter
            self.appendLog(logLine)


        if '*'== self.lineEdit.text():
            self.netlistdeal.showOriginNetMap()
            self.setTableViewModel(self.netlistdeal.originNetMap)
        else:
            self.netlistdeal.searchNet_fullName(self.lineEdit.text(), searchType= self.searchType)
            self.setTableViewModel(self.netlistdeal.searchResult)

        if self.searchType==0:
            logLine = 'Search '+ "'"+self.lineEdit.text()+"'"+ ' for Net, get results:'+str(len(self.netlistdeal.searchResult))
        else:
            logLine = 'Search '+ "'"+self.lineEdit.text()+"'"+ ' for LOC, get results:'+str(len(self.netlistdeal.searchResult))

        self.appendLog(logLine)
       

    # mapResult is like this: [(net1,loc1), (net2,loc2)]
    def setTableViewModel(self, mapResult):
        self.tableModel=QStandardItemModel(len(mapResult),3)
        self.tableModel.setHorizontalHeaderLabels(['Port','Net','LOC'])
        row_cnt=0
        for net_locMap in mapResult:
            
            item1=QStandardItem(net_locMap[0])
            item2=QStandardItem(net_locMap[1])
            #设置每个位置的文本值
            self.tableModel.setItem(row_cnt,1,item1)
            self.tableModel.setItem(row_cnt,2,item2)
            row_cnt = row_cnt + 1

        self.tableView.setModel(self.tableModel)
        self.tableView.setColumnWidth(0,150)
        self.tableView.setColumnWidth(1,250)
        self.tableView.setColumnWidth(2,260)
        # for index in [1,2]:
        # self.tableView.resizeColumnToContents(1)


    def appendLog(self, logString):
        self.logLines = self.logLines + logString+'\n'
        self.textEdit_log.setPlainText(self.logLines)

    # menu
    def tableViewMenu(self, point):
        rightMenu = QtWidgets.QMenu(self.menuBar)

        submenu = QtWidgets.QMenu('编辑Port', rightMenu)

        self.addselect = QtWidgets.QAction(self)
        self.addselect.setObjectName("addselect")
        self.addselect.setText(QtCore.QCoreApplication.translate("MainWindow", "选择为总线"))

        self.editPortName = QtWidgets.QAction(self)
        self.editPortName.setObjectName("editPortName")
        self.editPortName.setText(QtCore.QCoreApplication.translate("MainWindow", "手动编辑Port名称"))

        self.autoGenPortName = QtWidgets.QAction(self)
        self.autoGenPortName.setObjectName("autoGenPortName")
        self.autoGenPortName.setText(QtCore.QCoreApplication.translate("MainWindow", "自动生成Port名称"))

        self.genXDC = QtWidgets.QAction(self)
        self.genXDC.setObjectName("genXDC")
        self.genXDC.setText(QtCore.QCoreApplication.translate("MainWindow", "生成XDC"))

        self.printLOC = QtWidgets.QAction(self)
        self.printLOC.setObjectName("printLOC")
        self.printLOC.setText(QtCore.QCoreApplication.translate("MainWindow", "print LOC"))

        # for menuItem in \
        #     [
        #         self.addselect,
        #         self.genXDC
        #     ]:
        submenu.addAction(self.editPortName)
        submenu.addAction(self.autoGenPortName)


        rightMenu.addAction(self.addselect)
        rightMenu.addMenu(submenu)
        rightMenu.addAction(self.genXDC)
        rightMenu.addAction(self.printLOC)

        

        
        action=rightMenu.exec_(QtGui.QCursor.pos())
        if action==self.addselect:
            self.netBusProc()
        if action==self.genXDC:
            # self.onTableViewSelectedChanged()
            # self.showTableViewSelectedItems()
            self.showXDC()
        if action == self.printLOC:
            self.doPrintLOC()
            
        # for item in self.tableView.selectedItems():
        #     print(item)   
            

            
        # print(self.tableView.currentIndex().row())
    def doPrintLOC(self):
        self.getSelectedRow()

    def showXDC(self):
        
    #生成单行xdc
        self.pattDialog.show()
        if self.lineEdit_tpartName.text() != "":
            tableModel=self.tableView.model()
            data=tableModel.data(self.tableView.currentIndex())
            row_idx = self.tableView.currentIndex().row()
            portName_idx = tableModel.index(row_idx, 0)
            netName_idx = tableModel.index(row_idx, 1)
            netConn_idx = tableModel.index(row_idx, 2)

            portName = tableModel.data(portName_idx)
            netName = tableModel.data(netName_idx)
            netConn = tableModel.data(netConn_idx)

            

            #输入参数判空
            for cell in [portName, netName, netConn ]:
                if cell == None:
                    QMessageBox.question(self,"Warning","一个参数为空",
                                      QMessageBox.Ok|QMessageBox.Ok)
                    return

            #从net连接关系中获取loc

            netConn_arry = netConn.split(' ')
            tpartName = self.lineEdit_tpartName.text().upper()
            for netConn_cell in netConn_arry:
                if tpartName+'.' in netConn_cell:
                    loc = netConn_cell.replace(tpartName+'.', "")
                    print(loc)

            print(portName, netName, loc)

        else:
            QMessageBox.question(self,"Warning","未输入目标器件",
                                      QMessageBox.Ok|QMessageBox.Ok)
        # print(self.tableView.columnWidth(modelindex.row()))
        self.textWindow.textEdit.setPlainText('2333')
        # self.textWindow.show()
    def showTableViewSelectedItems(self):
        for index in self.selectedItemPos:
            qindex = self.tableView.model().index(index[0], index[1])
            itemData = self.tableView.model().data(qindex)
            print(itemData)
    def getSelectedRow(self):
        self.selectedRowNum.clear()
        for modelindex in self.tableView.selectedIndexes():
            self.selectedRowNum.append(modelindex.row())
        tableModel=self.tableView.model()
        print('***********************')
        self.appendLog('***********************')
        for row in self.selectedRowNum:
            idx_net = tableModel.index(row,1)
            idx_conn = tableModel.index(row,2)

            data_net = tableModel.data(idx_net)
            data_conn = tableModel.data(idx_conn)

            data_conn_arr = data_conn.split(' ')
            for item in data_conn_arr:
                if 'U1.' in item:
                    data_conn_p = item.replace('U1.', '')

            
            print(data_net, data_conn_p)
            self.appendLog(data_net+':  '+data_conn_p)
        self.appendLog('***********************')
        print('***********************')



    def onTableViewSelectedChanged(self):
        self.selectedItemPos.clear()
        for modelindex in self.tableView.selectedIndexes():
            # print(modelindex.row())
            
            self.selectedItemPos.append((modelindex.row(), modelindex.column()))
            tableModel=self.tableView.model()
            # print('model index is ')
            # print(modelindex)
            
            data=tableModel.data(modelindex)
            # print(modelindex.row(),modelindex.column())
            # print(data)
            idx = tableModel.index(10,2)
            data2= tableModel.data(idx)
            # print('data2  is ')
            # print(data2)
            # print(self.tableView.columnWidth(modelindex.row()))
        for item in self.selectedItemPos:
            
            print(self.tableView.rowAt(item[0]))
            
        print('\n')
    def netBusProc(self):
        # print(self.tableView.selectedIndexes())
        self.selectedItemPos.clear()
        for modelindex in self.tableView.selectedIndexes():
            # print(modelindex.row())
            
            self.selectedItemPos.append((modelindex.row(), modelindex.column()))
            tableModel=self.tableView.model()
            
            data=tableModel.data(modelindex)
            print(data)
            print(self.tableView.columnWidth(modelindex.row()))
        for item in self.selectedItemPos:
            
            print(self.tableView.rowAt(item[0]))
            
        print('\n')
        # self.selectedBusDict


if __name__ == '__main__': #如果整个程序是主程序
     # QApplication相当于main函数，也就是整个程序（很多文件）的主入口函数。
     # 对于GUI程序必须至少有一个这样的实例来让程序运行。
    app = QtWidgets.QApplication(sys.argv)
    #生成 mywindow 类的实例。
    window = mywindow()
    #有了实例，就得让它显示，show()是QWidget的方法，用于显示窗口。
    window.show()
    # 调用sys库的exit退出方法，条件是app.exec_()，也就是整个窗口关闭。
    # 有时候退出程序后，sys.exit(app.exec_())会报错，改用app.exec_()就没事
    # https://stackoverflow.com/questions/25719524/difference-between-sys-exitapp-exec-and-app-exec
    sys.exit(app.exec_())